<?php
class Photo_model extends MY_Model
{
	public
		$table = 'files',
		$prKey = 'file_ID'
	;
	
	public 
		$wwwPhotoDir = '/files/uploads/photo/products/',
		$tmpPhotoDir =  '/tmp/photos/'
	;
	
	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'photo_ID' => '',
			'photo_caption' => T_('Caption'),
		);

		$this->rules = array(
			'photo_caption' => "trim|strip_tags|max_length[255]",
		);
	}
	
	function getPhotos($table, $product_ID = null)
	{
		$this->wwwPhotoDir .= $product_ID . '/';
		$this->db->where('file_table', $table);
		$this->db->where('file_item_ID', $product_ID);
		$this->db->order_by('file_session_number_photo');

		return $this->db->get($this->table);
	}

	function getPhotoImage($file_ID = null, $width = 98, $height = 141)
	{
		$src = "/files/images/no_photo/{$width}x{$height}.jpg";
		
		if (!empty($file_ID)) 
		{
			$src = $this->wwwPhotoDir . "{$width}x{$height}/{$file_ID}.jpg";
		}
		
		return sprintf('<table align="center" class="superTable" width="%d" height="%d">
							<tr>
								<td>
									<img src="%s"/>
								</td>
							</tr>
						</table>', $width, $height, $src);
//		return sprintf('<img src="%s" width="%d" height="%d" />', $src, $width, $height);
	}	

	function getPhotoImage2($file_ID = null, $width = 98, $height = 141)
	{
		$src = "/files/images/no_photo/{$width}x{$height}.jpg";
		
		if (!empty($file_ID)) 
		{
			$src = $this->wwwPhotoDir . "{$width}x{$height}/{$file_ID}.jpg";
		}
		
		return sprintf('<img src="%s"/>', $src);
	}	

	function hasPhotos($product_ID)
	{
		$this->db->select('COUNT(file_ID) AS num');
		$this->db->where('file_table', 'products');
		$this->db->where('file_item_ID', $product_ID);
		$res = $this->db->get('files')->row();
		
		return $res->num;
	}

	function hasPhoto($product_ID, $number_photo)
	{
		$this->db->select('file_ID');
		$this->db->where('file_table', 'products');
		$this->db->where('file_item_ID', $product_ID);
		$this->db->where('file_session_number_photo', $number_photo);		
		$res = $this->db->get('files')->row();
		
		return $res->file_ID;
	}
		
	function hasCategoryPhoto($product_ID, $number_photo)
	{
		$this->db->select('file_ID');
		$this->db->where('file_table', 'categories');
		$this->db->where('file_item_ID', $product_ID);
		$this->db->where('file_session_number_photo', $number_photo);		
		$res = $this->db->get('files')->row();
		
		return $res->file_ID;
	}
	
	function insert($data = array())
	{
		$this->wwwPhotoDir .= $data['file_item_ID'] . '/';
		
		$config['upload_path'] = BASEPATH . $this->tmpPhotoDir;
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '12000';
		$config['max_width'] = '4000';
		$config['max_height'] = '3000';
		
		$this->load->library('upload', $config);

		if ($this->upload->do_upload())
		{
			$uploadedFile = $this->upload->data();
			
			if (!$uploadedFile['is_image'])
			{
				@unlink($uploadedFile['full_path']);
				return false;
			}

			if ($this->photo_model->hasPhotos($data['file_item_ID']) > 0)
			{
				$data['file_main'] = 0;	
			}
			else
			{
				$data['file_main'] = 1;	
			}			
					
			$data['file_name'] = $uploadedFile['file_name'];
			$data['file_mime'] = $uploadedFile['file_type'];
			$data['file_dir'] = 'uploads/photo/products/'.$data['file_item_ID'].'/';
			
			$data['file_width'] = $uploadedFile['image_width'];
			$data['file_height'] = $uploadedFile['image_height'];

			$photo_ID = parent::insert($data);

			@mkdir('..' . $this->wwwPhotoDir, 0777);
			
			$this->load->library('image_lib'); 
	
			$schemes = $this->config->item('thumb_schemes');
			$settings = $this->config->item('thumb_settings');
	
			$settings['source_image'] = $uploadedFile['full_path'];
			
			foreach ($schemes as $key => $scheme)
			{

				foreach ($scheme as $param => $value)
				{
					$settings[$param] = $value;
				}
				
				@mkdir('..' . $this->wwwPhotoDir . $key, 0777);
				$settings['new_image'] = '..' . $this->wwwPhotoDir . $key . '/' . $photo_ID . '.jpg'; 

				$this->image_lib->initialize($settings);
				
				if ( $this->image_lib->image_process_gd_add_background('resize', $scheme['width'], $scheme['height']))
				{
//					copy($settings['source_image'], '../files/uploads/photo/products/'.$this->product_ID.'/'.$this->filename);
				}
				else
				{
//					echo $this->image_lib->display_errors();
				} 						
			}
			
			//TODO: does not work when upload picture with same filename 
			rename($uploadedFile['full_path'], '..' . $this->wwwPhotoDir .'/'.$uploadedFile['file_name']);

			return $photo_ID;
		}
		
		return false;
	}
	
	function delete($photo_IDs = array())
	{
		foreach ($photo_IDs as $ID)
		{
			parent::delete($ID);
			
			$dir = '..' . $this->wwwPhotoDir . $ID;
			
			if ($objs = glob($dir."/*"))
			{
				foreach ($objs as $obj)
				{
					@unlink($obj);
				}
	
				@rmdir($dir);
		    }
		}
	}
	
	function deleteProductPhoto($file_ID)
	{
		/*
		$this->db->select('file_dir');
		$this->db->where('file_ID', $file_ID);
		$this->db->where('file_table', 'products');
		$file = $this->db->get($this->table)->row_array();

		@unlink('/files/' . $file['file_dir'] . $file_ID . '.jpg');
		*/
		
		parent::delete($file_ID);
	}	
	
	function deleteCategoryPhoto($file_ID)
	{
		parent::delete($file_ID);
	}
	
	function getTempPhotos($session_key)
	{
		$this->db->where('file_table', 'products');
		$this->db->where('file_session_ID', $session_key);
		$this->db->order_by('file_session_number_photo');
		$res = $this->db->get($this->table)->result_array();

		return $res;
	}

	function getTempCategoryPhotos($session_key)
	{
		$this->db->where('file_table', 'categories');
		$this->db->where('file_session_ID', $session_key);
		$this->db->order_by('file_session_number_photo');
		$res = $this->db->get($this->table)->result_array();

		return $res;
	}
	
	function renameTempFolder($product_ID, $session_key)
	{		
		$data = array(
               'file_item_ID' => $product_ID,
               'file_dir' => 'uploads/photo/products/' . $product_ID . '/',
               'file_session_ID' => ''
            );
		
		$this->db->where('file_table', 'products');
		$this->db->where('file_session_ID', $session_key);

		return $this->db->update($this->table, $data);
	}	
	
	function renameTempCategoryFolder($product_ID, $session_key)
	{		
		$data = array(
               'file_item_ID' => $product_ID,
               'file_dir' => 'uploads/photo/categories/' . $product_ID . '/',
               'file_session_ID' => ''
            );
		
		$this->db->where('file_table', 'categories');
		$this->db->where('file_session_ID', $session_key);

		return $this->db->update($this->table, $data);
	}
}
?>